<template>
  <div class="messageviewing">
    <!-- 报文查看 messageViewing-->
        <div class="con">
              <div class="left-tree">
                 <el-scrollbar style="height:calc(100% - 30px);width: 100%;">
                  <!-- default-expand-all -->
                    <el-tree class="filter-tree" :data="dataList"  
                        :expand-on-click-node="true" 
                        @node-click='treeClick'
                        default-expand-all
                        node-key="myid" :props="defaultProps" :highlight-current='true'  ref="tree" 
                    >
                    <template #default="{ node }">
                        <div class="custom-tree-node">
                            <div class="flexitem">
                                 <img src="../../assets/btnImg/2.0.png" alt="" v-if="node.data.level == 1">
                                 <img src="../../assets/btnImg/2.1.png" alt="" v-if="node.data.mytype == 'device'">
                                 <img src="../../assets/btnImg/group.png" alt="" v-if="node.data.mytype == 'channel'">
                                 {{ node.label }}
                            </div>
                        </div>
                      
                    </template>
                    </el-tree>
                    </el-scrollbar>
              </div>
              <div class="right-table">
                   <div class="topradio">
                       <div class="left-nav">
                            <el-radio v-model="radio" label="1">显示源码（{{nowDeviceItem.treeName}}）</el-radio>
                            <!-- <el-radio v-model="radio" label="2">显示全部设备</el-radio> -->
                        </div>
                        <div class="right-btn">
                            <div class="rownum" >
                                <!-- v-show="downloadFlag" -->
                                <!-- @click="startTimer" -->
                                <!-- <el-input v-model.number="rowsNumber" placeholder="[整型数字]" style="width:100px"></el-input> -->
                                <el-button type="primary"  @click="startSaving(1)">开始录制</el-button>
                                <div class="downtxt">时间：{{formattedTime}}</div>
                                <el-button type="primary" @click="stopTimer(1)">结束录制并下载</el-button>
                            </div>
                            <!-- <el-button @click="downloadPhased(1)" type="primary" v-show="downloadFlag">下载源码</el-button> -->
                            <el-button @click="connectfn" type="primary" class="last-el-button">{{lianjieTitle}}</el-button>
                        </div>
                   </div>
                   <draggable-box
      v-for="(box, index) in boxes"
      :key="index"
      :title="box.device_name"
      :devicenumber="box.device_number"
      :deviceid="box.device_id"
      :lefttype='box.leftType'
      :initialPosition="box.position"
      @remove-box="removeBox(index)"
      @move-box="moveBox"
    >
    <!-- v-show="box.download" -->
    <div class="dounrow">
        <el-button type="primary"  @click="startSaving(2,box)">开始录制</el-button>
        <div class="downtxt">时间：{{box.formattedTime}}</div>
         <el-button type="primary" @click="stopTimer(2,box)">结束录制并下载</el-button>
        <!-- <div class="downtxt">行数：</div>
         <el-input v-model.number="box.rowsNumber" placeholder="[整型数字]" style="width:100px"></el-input>
         <div class="xiazaiyuanma"  @click="downloadPhased(2,box)">下载源码</div> -->
    </div>
    <!-- messageList -->
    <div class="chuangkou" @contextmenu.prevent="showContextMenu(2,$event,index)">
         <div
             v-show="box.contextMenuVisible"
             class="context-menu"
             :style="{ top: box.contextMenuTop + 'px', left: box.contextMenuLeft + 'px' }"
             @click="handleContextMenuClick">
            <ul>
                <li @click="switchScrolling(2,box)">{{box.zidongflag ? '自动滚动':'手动滚动'}}</li>
                <li @click="zanting(2,box)">{{box.stopFlag ? '继续':'暂停'}}</li>
                <li @click="qingkong(2,box)">清空源码</li>
                <!-- <li @click="startSaving(2,box)">保存源码</li> -->
            </ul>
        </div>
         <el-scrollbar :class="box.elementName"   style="height:calc(100% - 10px);width: 100%;" ref="scrollbar">
        
          <div id="targetElementss">
                <div class="conitem" v-for="(item,i) in box.messageList" :key="i+100">
                      <div class="texts" :style="{'color':item.mycolor}">{{item.msg}}</div>
                </div>
        </div>
     </el-scrollbar>
    </div>
      
    </draggable-box>
                   <div class="rightcon" @contextmenu.prevent="showContextMenu(1,$event)">
                      <div
                                v-if="contextMenuVisible"
                                class="context-menu"
                                :style="{ top: contextMenuTop + 'px', left: contextMenuLeft + 'px' }"
                                @click="handleContextMenuClick"
                                >
                                <ul>
                                    <li @click="addBox">窗口化</li>
                                    <li @click="switchScrolling(1)">{{zidongflag ? '自动滚动':'手动滚动'}}</li>
                                    <li @click="zanting(1)">{{stopFlag ? '继续':'暂停'}}</li>
                                    <li @click="qingkong(1)">清空源码</li>
                                    <!-- <li @click="startSaving(1)">保存源码</li> -->
                                </ul>
                                </div>
                      <el-scrollbar style="height:calc(100% - 10px);width: 100%;">
                       
                          <div id="targetElements">
                            <div class="conitem" v-for="(item,index) in leftTable" :key="index">
                                  <div class="texts" :style="{'color':item.mycolor}">{{item.msg}}</div>
                            </div>
                          </div>
                       </el-scrollbar>
                   </div>
              </div>
        </div>
  </div>
</template>

<script>
import DraggableBox from '../../components/module/DraggableBox.vue';
import {findchannelconfigAll,transmitChannelList} from "../../api/dataComparisonApi";
import {getDeviceList,commondatatype} from "../../api/Interface";
import { useCounterStore } from '../../stores/counter'
import { onBeforeUnmount , ref} from "vue";
export default {
    setup() {
    const ws = ref(null);
    const timerNull = ref(null);
    const changshi = ref(null);
    onBeforeUnmount(() => {
      clearTimeout(changshi.value)
      clearInterval(timerNull.value)
      if (ws.value) {
          const params = 'close';
          ws.value.send(params);
          ws.value.close();
      }
    });
    return {
     ws,
     changshi,
     timerNull
    };
   },
    components: {
        DraggableBox
    },

  data() {
    return { 
        formattedTime:'00:00:00',
        startTime: null,//计时器
        elapsedTime: 0,//计时器
        rowsNumber:10,
        contextMenuVisible: false,
        contextMenuTop: 0,
        contextMenuLeft: 0,
        downloadFlag:false,
        //窗口化
        boxElementArr:[],
        boxes: [
            // { title: '设备1', messageList:[], position: { top: 100, left: 100 } }
        ],
        radio:"1",
        isMask:false,//缓冲
        deviceArr:[],//设备数据
        // optionsType:[],//数据类型
        tabindex:1,
        total:0,
        currentPage:1,
        data_bitsList:[],
        leftTable:[],
        optionsFang:[],
        versionsName:"",
        dataList:[
            {
                'treeName':"数据采集",
                'children':[
                    {
                     'treeName':"采集通道",
                     'children':[],
                    },
                    {
                     'treeName':"转发通道",
                     'children':[],
                    },
                ],
                "myid":1000000001
            }
        ],
        dataListCopy:[
            {
                'treeName':"数据采集",
                'channels':[
                    {
                     'treeName':"采集通道",
                     'channels':[],
                    },
                    {
                     'treeName':"转发通道",
                     'channels':[],
                    },
                ],
                "myid":1000000001
            }
        ],
        nowDeviceItem:{},//树形结构
          defaultProps: {
            children: 'channels',
            label: 'treeName',
        },
        addDecive:false,//变量编辑
        checked:true,
        addDecivebian:false,//新增变量
        piliangEdit:false,//批量修改
        deviceDataAll:[],//集合返回的设备数据
        channelDataAll:[],//集合返回的全部通道(采集通道和转发通道)数据
        // ws: null,
        message: null,
        caijiShebei:[],
        panduanFlag:false,
        targetElement:null,
        stopFlag:false,//暂停跟继续
        zidongflag:true,
        newbaseUrl:"",
        lianjieFlag:false,
        lianjieTitle:"连接",
        boxIndex:-1, 
        leftType:'通道',
        isDirty:true
        };
  },

  mounted() {
     var currentUrl = window.location.href;
   var baseUrl = currentUrl.substring(0, currentUrl.indexOf('/#'));
   // 获取端口号
      var port = window.location.port;
      // 去掉端口号
      if (port !== '') {
      baseUrl = baseUrl.replace(':' + port, '');
      }
      // 使用正则表达式去掉开头的'//'
     this.newbaseUrl =  baseUrl.replace(/^(https?:\/\/)/, '');
    this.getDeviceListData()
    // this.getcommondatatype()
     this.targetElement = document.getElementById('targetElements')
  },
  beforeDestroy () {
     if(this.panduanFlag){
        this.disconnect()
     }
  },
  computed: {
       optionsType(){
          return useCounterStore().mydataType
       },
  },
  beforeRouteLeave(to, from, next) {
    const hasAdmin = this.boxes.some(user => user.download);
    if (this.downloadFlag || hasAdmin) {
      // 如果页面有未保存的更改，弹出确认对话框
      this.$confirm('你有保存的源码，需要下载源码并离开吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 用户确认离开，调用 next() 方法继续跳转
        if(this.downloadFlag){
              this.downloadPhased(1)
        }
        if(hasAdmin){
            this.boxes.forEach(item => {
                 if(item.download){
                     this.downloadPhased(2,item)
                 }
            })
        }
        next();
      }).catch(() => {
        // 用户取消离开，调用 next(false) 阻止跳转
        var arr1 = this.$store.menuStore.state.preventRouter
        arr1++
        this.$store.menuStore.commit("setPreventRouter",arr1)
        next(false);
        
      });
    } else {
      // 页面没有未保存的更改，直接允许跳转
      next();
    }
  },
  watch: {
    // 侦听leftTable的变化,超出50条，就删除前20条
    leftTable(newVal) {
       if(newVal.length > 150){
          this.leftTable = this.leftTable.filter((item,index) => index > 30)
       }
    }
  },
  
  methods: {
        //计时器
        padTime(time) {
          return time.toString().padStart(2, '0')
        },
        startTimer() {
           if (this.timerNull) return
        
            this.startTime = Date.now() - this.elapsedTime
            this.timerNull = setInterval(() => {
                this.elapsedTime = Date.now() - this.startTime
                const totalSeconds = Math.floor(this.elapsedTime / 1000)
                const hours = Math.floor(totalSeconds / 3600)
                const minutes = Math.floor((totalSeconds % 3600) / 60)
                const seconds = totalSeconds % 60
               this.formattedTime =  `${this.padTime(hours)}:${this.padTime(minutes)}:${this.padTime(seconds)}`

            }, 1000)
        },
        stopTimer(type,row) {
            clearInterval(this.timerNull)
            this.elapsedTime = 0
            this.formattedTime = '00:00:00'
            if(type == 1){
                this.downloadPhased(1)
            }else {
                 this.downloadPhased(2,row)
            }
        },
        showContextMenu(type,event,index) {
            // console.log("event",event);
            if(type == 1){
                this.contextMenuTop = event.layerY + 20;
                this.contextMenuLeft = event.layerX;
                this.contextMenuVisible = true;
                this.boxIndex = -1
            }else {
                this.boxes[index].contextMenuTop = event.layerY + 10
                this.boxes[index].contextMenuLeft = event.layerX
                this.boxes[index].contextMenuVisible = true
                this.boxIndex = index
            }
            window.addEventListener('click', this.hideContextMenu);
        },
        hideContextMenu() {
            if(this.boxIndex != -1){
                this.boxes[this.boxIndex].contextMenuVisible = false
            }
            this.contextMenuVisible = false;
            window.removeEventListener('click', this.hideContextMenu);
        },
        handleContextMenuClick(event) {
              event.stopPropagation();
        },
        //窗口化
        addBox() {
           if(Object.keys(this.nowDeviceItem).length === 0){
             this.$message({showClose: true,message: '请选择需要窗口化的通道或者设备',type: 'warning'});
             return
           }
           this.boxElementArr = []
        //    console.log("全部设备的报文",this.deviceDataAll);
           var myfindIndex = -1
           if(this.leftType == '设备'){
               myfindIndex = this.boxes.findIndex(item => item.device_number == this.nowDeviceItem.device_number && item.device_id == this.nowDeviceItem.device_id)
           }else if(this.leftType == '通道'){
               myfindIndex = this.boxes.findIndex(item => item.channel_id  && item.device_number == this.nowDeviceItem.channel_number)
           }
           if(myfindIndex != -1){
              return
           }
           
           if(this.leftType == '设备'){
              var findArr = this.deviceDataAll.filter(item => item.device_number == this.nowDeviceItem.device_number && item.device_id == this.nowDeviceItem.device_id)
              findArr[0].leftType = '设备'
           }else {
              var findArr = this.channelDataAll.filter(item => item.channel_number == this.nowDeviceItem.channel_number)
              findArr[0].leftType = '通道'
              findArr[0].device_id = findArr[0].channel_id
              findArr[0].device_number = findArr[0].channel_number
           }
           findArr[0].position= { top: 100, left: 100 } 
           findArr[0].elementName = `scrollbar${this.boxes.length + 1}`
           this.boxes.push(findArr[0])
        //    console.log("设备窗口化findArr[0]",findArr[0]);
        //    console.log("全部窗口化数据",this.boxes);
           this.$nextTick(() => {
                var elementbox = ""
                this.boxes.forEach(item => {
                     elementbox = document.querySelector(`.${item.elementName}`)
                      if(item.leftType == '设备'){
                         this.boxElementArr.push({
                            device_number:item.device_number,
                            device_id:item.device_id,
                            type:"设备",
                            element:elementbox.querySelector('.el-scrollbar__wrap')
                        })
                      }else {
                         this.boxElementArr.push({
                            device_number:item.channel_number,
                            device_id:item.channel_id,
                            channel_id:item.channel_id,
                            type:"通道",
                            element:elementbox.querySelector('.el-scrollbar__wrap')
                        })
                      }
                      
                })
                
                // console.log("this.boxElementArr",this.boxElementArr);
           })
           this.contextMenuVisible = false
           this.leftTable = []
        //   setTimeout(() => {
           
        //   },200)
           

        },
        moveBox(xyposition,num,id,type){
            // console.log(xyposition,num,id,type);
           if(type == '设备'){
               var myfindIndex = this.boxes.findIndex(item => item.leftType == '设备' && item.device_number == num && item.device_id == id)
           }else {
              var myfindIndex = this.boxes.findIndex(item => item.leftType == '通道' && item.channel_number == num)
           }
           this.boxes[myfindIndex].position = xyposition
        },
        //关闭弹窗
        removeBox(index) {
           if(this.boxes[index].download){
               this.$confirm(`${this.boxes[index].device_name} 已开始保存源码，是否要下载`,'提示',{
                confirmButtonText: '确定下载并关闭',
                cancelButtonText: '取消下载',
                type: 'warning'
                }).then(() => {
                   this.downloadPhased(2,this.boxes[index])
                   this.boxes = this.boxes.filter((item,i) => i != index)
                }).catch(() => {
                   this.boxes = this.boxes.filter((item,i) => i != index)
                });
           }else {
              this.boxes = this.boxes.filter((item,i) => i != index)
           }
        },
        handleSizeChangejiao(){},
        handleCurrentChangejiao(){},
         //获取数据类型
        getcommondatatype(){
            commondatatype().then(res => {
                // console.log("数据类型",res);
                  this.optionsType = res
            })
        },
       
         //获取表格列表
        getfindchannelconfigAll(){
            this.channelDataAll = []
            findchannelconfigAll().then(res => {
            this.isMask = false
            if(res != undefined){
                var arr1 = []
                res.forEach((item,index) => {
                    // channel_number
                     item.treeName = item.channel_name
                     item.mytype = 'channel'
                     item.channels = this.deviceArr.filter(tt => tt.channel_number == item.channel_number)
                     item.myid = 1000000+index
                     arr1.push({
                        'device_name':item.channel_name,
                        'channel_number':item.channel_number,
                        'channel_id':item.channel_id,
                        'messageList':[],
                        'messageListAll':[],
                        'contextMenuVisible':false,
                        'contextMenuTop':0,
                        'contextMenuLeft':0,
                        'formattedTime':'00:00:00',
                        'timerNull':null,
                        'zidongflag':true,
                        'stopFlag':false,
                        'download':false,
                        'rowsNumber':"",
                        'downloadList':[]
                     })
                })
                this.caijiShebei = res
                this.channelDataAll = arr1
                // this.dataListCopy[0].children[0].children = res
                // this.dataList = JSON.parse(JSON.stringify(this.dataListCopy))
                // console.log("树形结构",this.dataList);
                this.getzhuanfaList()
            }
            
            }).catch(() => {
                  this.isMask = false
              })
        },
        //获取所有设备
        getDeviceListData(){
             this.isMask = true
              getDeviceList().then(res => {
                   if(res != undefined){
                    var arr1 = []
                    res.forEach((item,index) => {
                         item.treeName = item.device_name
                         item.children = []
                         item.mytype = 'device'
                         item.myid = 10000000+index
                         arr1.push({
                            'device_id':item.device_id,
                            'device_name':item.device_name,
                            'device_number':item.device_number,
                            'channel_number':item.channel_number,
                            'messageList':[],
                            messageListAll:[],
                             contextMenuVisible:false,
                             'formattedTime':'00:00:00',
                            'timerNull':null,
                            contextMenuTop:0,
                            contextMenuLeft:0,
                            zidongflag:true,
                            stopFlag:false,
                            'download':false,
                            'rowsNumber':"",
                            'downloadList':[]
                         })
                    })
                       this.deviceDataAll = arr1
                       this.deviceArr = res
                       this.getfindchannelconfigAll()
                   }
              }).catch(() => {
                  this.isMask = false
              })
        },
         //获取转发通道列表
        getzhuanfaList(){
            // console.log("获取转发通道");
            this.isMask = true
           this.dataListCopy = [
            {
                'treeName':"数据采集",
                'channels':[
                    {
                     'treeName':"采集通道",
                     'channels':[],
                     'mytype':'channel'
                    },
                    {
                     'treeName':"转发通道",
                     'channels':[],
                     'mytype':'channel'
                    },
                ],
                "myid":1000000001
            }
           ]
           transmitChannelList().then(res => {
              this.isMask = false
            //   console.log("转发通道列表",res);
            //   return
              //扩展参数根据extend_type来判断,大于0才有扩展参数，设备信息都有
              //所属区域先定死个默认区域传0，设备组就是设备模板的模板组，设备子模板就是设备模板，设备子系列也在设备模板页面
              //设备规约就是通道规约，然后不选的话，就沿用通道的规约
              var devExtendType = ""
              var agreementId = ""
              var arr1 = []
              var myid = 1
               var recursiveFunction=function() {
                const getStr=function(list) {
                    list.forEach(function(row) {
                    if(row.channels && row.channels.length != 0) {
                        // console.log("有通道的协议",row);
                        devExtendType = row.extend_type
                        agreementId = row.id
                        row.channelName = row.name
                        row.treeName = row.name
                        row.myid = myid++
                        row.mytype = 'channels'
                        row.level = 1
                        getStr(row.channels)
                    } else {
                        if(row.hasOwnProperty('extend_type')) {
                        //    console.log("无通道的协议",row);
                           devExtendType = row.extend_type
                           row.channelName = row.name
                           row.treeName = row.name
                           row.mytype = 'channels'
                           row.myid = myid++
                           row.level = 1
                       }else {
                          if(row.hasOwnProperty('devices')){
                                // console.log("协议下的通道",row);
                                row.channels = row.devices
                                row.channelName = row.channel_name
                                row.treeName = row.channel_name
                                row.mytype = 'channel'
                                row.myid = myid++
                                row.level = 2
                                arr1.push({
                                    'device_name':row.channel_name,
                                    'channel_number':row.channel_number,
                                    'channel_id':row.channel_id,
                                    'messageList':[],
                                    'messageListAll':[],
                                    'contextMenuVisible':false,
                                    'contextMenuTop':0,
                                    'contextMenuLeft':0,
                                    'zidongflag':true,
                                    'stopFlag':false,
                                    'download':false,
                                    'rowsNumber':"",
                                    'downloadList':[]
                                })
                                getStr(row.devices)
                            }else {
                                //  console.log("通道下的设备",row)
                                 row.channelName = row.device_name
                                 row.treeName = row.device_name
                                 row.level = 3
                                 row.myid = myid++
                                 row.devAgreementId = agreementId
                                 row.devType = devExtendType
                                 row.mytype = 'device'
                            }
                       } 
                    }
                    })
                }
                getStr(res)
                }
                recursiveFunction()
                this.channelDataAll = this.channelDataAll.concat(arr1)
                // console.log("转发通道",res)
                 this.dataListCopy = [
                        {
                            'treeName':"数据采集",
                            'channels':[
                                {
                                'treeName':"采集通道",
                                'channels':this.caijiShebei,
                                'mytype':'channel'
                                },
                                {
                                'treeName':"转发通道",
                                'channels':res,
                                'mytype':'channel'
                                },
                            ],
                            "myid":1000000001
                        }
                    ]
                // this.dataListCopy[0].children[0].children = this.caijiShebei
                // this.dataListCopy[1].children[0].children = res
                // console.log("this.dataListCopy",this.dataListCopy)
                 this.dataList = JSON.parse(JSON.stringify(this.dataListCopy))
                    // console.log("this.dataList",this.dataList);
                // this.dataList[0].channels = res
           }).catch(() => {
              this.isMask = false
           })
        },
        
         //树形结构点击
        treeClick(row){
             this.nowDeviceItem = row
            //  console.log("当前设备",row);
           
             if(row.mytype == 'device'){
                // this.isMask = true
                this.leftType = '设备'
                var findArr = this.deviceDataAll.filter(item => item.device_number == row.device_number && item.device_id == row.device_id)
                //判断是否开启了窗口化
                var boxArr = this.boxes.filter(item => item.leftType == '设备' && item.channel_number == this.nowDeviceItem.channel_number && item.device_id == this.nowDeviceItem.device_id)
                if(boxArr.length == 0){
                      this.leftTable = JSON.parse(JSON.stringify(findArr[0].messageList))
                }
                // if(!this.panduanFlag){
                //     this.connect()
                // }
             }else {
                  if(row.channel_number){
                    //   console.log("当前通道",row);
                    //   console.log("设备集合",this.deviceDataAll);
                      this.leftType = '通道'
                      var messageArr = this.channelDataAll.filter(item => item.channel_number == row.channel_number)
                      //判断是否开启了窗口化
                    var boxArr = this.boxes.filter(item => item.leftType == '通道' && item.channel_number == this.nowDeviceItem.channel_number)
                    if(boxArr.length == 0){
                       this.leftTable = JSON.parse(JSON.stringify(messageArr[0].messageList))
                    }else {
                        this.leftTable = []
                    }
                      
                     
                  }else {
                      this.leftTable = []
                  }
                  this.total = 0
                //   if(this.panduanFlag){
                //       this.disconnect()
                //   }
             }
        },
        //切换滚动(type == 1是最大那个，!= 1则是窗口)
        switchScrolling(type,row){
           if(type == 1){
             this.zidongflag = !this.zidongflag
             this.contextMenuVisible = false;
           }else {
            //设备
                 if(row.leftType == '设备'){
                      var myIndex = this.deviceDataAll.findIndex(item => item.channel_number == row.channel_number && item.device_number == row.device_number)
                     this.deviceDataAll[myIndex].zidongflag = !this.deviceDataAll[myIndex].zidongflag
                       this.deviceDataAll[myIndex].contextMenuVisible = false
                 }else { //通道
                    var myIndex = this.channelDataAll.findIndex(item => item.channel_number == row.channel_number)
                    this.channelDataAll[myIndex].zidongflag = !this.channelDataAll[myIndex].zidongflag
                      this.channelDataAll[myIndex].contextMenuVisible = false
                 }
               
             
           }
        },
        //暂停
        zanting(type,row){
            // console.log("this.leftTable",this.leftTable);
            if(type == 1){
                 this.stopFlag = !this.stopFlag
                 //设备
                 if(this.leftType == '设备'){
                    var myIndex = this.deviceDataAll.findIndex(item => item.channel_number == this.nowDeviceItem.channel_number && item.device_number == this.nowDeviceItem.device_number)
                    this.deviceDataAll[myIndex].stopFlag = this.stopFlag
                 }else { //通道
                    var myIndex = this.channelDataAll.findIndex(item => item.channel_number == this.nowDeviceItem.channel_number)
                    this.channelDataAll[myIndex].stopFlag = this.stopFlag
                 }
             
                 this.contextMenuVisible = false;
            }else {
                //设备
                 if(row.leftType == '设备'){
                      var myIndex = this.deviceDataAll.findIndex(item => item.channel_number == row.channel_number && item.device_id == row.device_id)
                      this.deviceDataAll[myIndex].stopFlag = !this.deviceDataAll[myIndex].stopFlag
                       this.deviceDataAll[myIndex].contextMenuVisible = false
                 }else { //通道
                    var myIndex = this.channelDataAll.findIndex(item => item.channel_number == row.channel_number)
                    this.channelDataAll[myIndex].stopFlag = !this.channelDataAll[myIndex].stopFlag
                    this.channelDataAll[myIndex].contextMenuVisible = false
                 }
              
              
            }
        },
        //清空
        qingkong(type,row){

            if(type == 1){
                if(this.leftType == '设备'){
                  var myIndex = this.deviceDataAll.findIndex(item => item.channel_number == this.nowDeviceItem.channel_number && item.device_number == this.nowDeviceItem.device_number)
                  this.deviceDataAll[myIndex].messageList = []
                  this.deviceDataAll[myIndex].messageListAll = []
                }else {
                  var myIndex = this.channelDataAll.findIndex(item => item.channel_number == this.nowDeviceItem.channel_number)
                  this.channelDataAll[myIndex].messageList = []
                  this.channelDataAll[myIndex].messageListAll = []
                }
                this.leftTable = []
                this.contextMenuVisible = false;
            }else {
                if(row.leftType == '设备'){
                   var myIndex = this.deviceDataAll.findIndex(item => item.channel_number == row.channel_number && item.device_id == row.device_id)
                   this.deviceDataAll[myIndex].messageList = []
                   this.deviceDataAll[myIndex].messageListAll = []
                   this.deviceDataAll[myIndex].contextMenuVisible = false
                }else {
                  var myIndex = this.channelDataAll.findIndex(item => item.channel_number == row.channel_number)
                  this.channelDataAll[myIndex].messageList = []
                  this.channelDataAll[myIndex].messageListAll = []
                  this.channelDataAll[myIndex].contextMenuVisible = false
                }
                
            }
        },

        //连接
        connectfn(){
          if(this.lianjieFlag){
            return
          }
          if(!this.panduanFlag){
              this.connect()
          }else {
            this.disconnect()
          }
        },
        //连接
        connect() {
            // 创建WebSocket连接
            // this.ws = new WebSocket('ws://192.168.1.74:8005/server');
            if(import.meta.env.MODE == 'development'){
                this.ws = new WebSocket('ws://192.168.1.187:8005/server');
            }else {
                this.ws = new WebSocket(`ws://${this.newbaseUrl}:8005/server`)
            }
            // this.ws = new WebSocket(`ws://${this.newbaseUrl}:8005/server`);
            // 连接打开时的事件
            this.ws.onopen = (event) => {
                // console.log('WebSocket连接已打开：', event);
                this.lianjieFlag = true // 发送连接请求
                clearTimeout(this.changshi)
                this.lianjieTitle = '正在连接'
                if(event.type == 'open'){
                    // console.log("成功");
                    this.$message({showClose: true,message: '连接成功',type: 'success'});
                    this.sendMessage()
                }else {
                    this.lianjieFlag = false // 发送连接请求
                }
            };
            // 接收到消息时的事件
            this.ws.onmessage = (event) => {
                this.panduanFlag = true
                this.lianjieFlag = false // 发送连接请求
                this.lianjieTitle = "断开连接"
                if(event.data == 'expectation: [actulValue / monitor / close]'){
                    return
                }
                if(event.data == 'ok'){
                    return
                }
                if(event.data == 'error'){
                    this.$message({showClose: true,message: '通讯异常',type: 'error'});
                    this.disconnect()
                    return
                }
                if(event.data[0] != '{'){
                    return
                }
                var resData = JSON.parse(event.data)
                // console.log("resData",resData);
                if(resData.msg.includes('receive')){
                     resData.mycolor = '#67c23a'
                }else if(resData.msg.includes('Send')){
                     resData.mycolor = '#67c23a'
                }else {
                     resData.mycolor = '#f56c6c'
                }
                    //设备
                    var myIndex = this.deviceDataAll.findIndex(item => item.channel_number == resData.channel_id && item.device_number == resData.device_id)
                    if(!this.deviceDataAll[myIndex].stopFlag){//判断窗口是否暂停
                        this.deviceDataAll[myIndex].messageList.push(resData)
                        // this.deviceDataAll[myIndex].messageListAll.push(resData)
                        if(this.deviceDataAll[myIndex].messageList.length > 150){
                            this.deviceDataAll[myIndex].messageList = this.deviceDataAll[myIndex].messageList.filter((item,index) => index > 30)
                        }
                        if(this.deviceDataAll[myIndex].download){
                           this.deviceDataAll[myIndex].messageListAll.push(resData)
                        }
                    }
                    //通道
                    var myIndexChanne = this.channelDataAll.findIndex(item => item.channel_number == resData.channel_id)
                    if(!this.channelDataAll[myIndexChanne].stopFlag){//判断窗口是否暂停
                        this.channelDataAll[myIndexChanne].messageList.push(resData)
                        // this.channelDataAll[myIndexChanne].messageListAll.push(resData)
                        if(this.channelDataAll[myIndexChanne].messageList.length > 150){
                           this.channelDataAll[myIndexChanne].messageList = this.channelDataAll[myIndexChanne].messageList.filter((item,index) => index > 30)
                        }
                        if(this.channelDataAll[myIndexChanne].download){
                           this.channelDataAll[myIndexChanne].messageListAll.push(resData)
                        }
                    }
                //判断是否暂停
                if(!this.stopFlag){
                    //判断是展示通道/某个设备/全部设备
                    if(this.leftType == '通道'){
                     if(resData.channel_id == this.nowDeviceItem.channel_number){
                         var boxArr = this.boxes.filter(item => item.leftType == '通道' && item.channel_number == this.nowDeviceItem.channel_number)
                        if(boxArr.length == 0){
                            this.leftTable.push(resData)
                        }
                        
                     }
                    }else if(this.leftType == '设备'){
                        if(resData.channel_id == this.nowDeviceItem.channel_number && resData.device_id == this.nowDeviceItem.device_number){
                                var boxArr = this.boxes.filter(item => item.leftType == '设备' && item.channel_number == this.nowDeviceItem.channel_number && item.device_number == this.nowDeviceItem.device_number)
                                if(boxArr.length == 0){
                                    this.leftTable.push(resData)
                                }
                        }
                    }else if(this.leftType == '全部设备'){
                        // this.leftTable.push(resData)
                    }
                }
                
                //判断窗口是否自动滚动
                if(this.zidongflag){
                       setTimeout(() => {
                             this.targetElement.scrollIntoView({ behavior: 'smooth', block: 'end' })
                      },100)
                }
               
                //窗口自动滚动
                 this.$nextTick(() => {
                    var myIndex = -1
                    this.boxElementArr.forEach(boxitem => {
                        if(boxitem.type == '设备'){
                             myIndex = this.deviceDataAll.findIndex(item => item.device_number == boxitem.device_number)
                            if(this.deviceDataAll[myIndex].zidongflag){
                                boxitem.element.scrollTop = boxitem.element.scrollHeight
                            }
                        }else {
                            myIndex = this.channelDataAll.findIndex(item => item.channel_number == boxitem.device_number)
                            if(this.channelDataAll[myIndex].zidongflag){
                                boxitem.element.scrollTop = boxitem.element.scrollHeight
                            } 
                        }
                        
                        
                    })
                });
            };

            // 连接关闭时的事件
            this.ws.onclose = (event) => {
                console.log('WebSocket连接已关闭：', event);
            };

            // 连接出错时的事件
            this.ws.onerror = (error) => {

                console.error('WebSocket连接出现错误：', error);
                this.$message({showClose: true,message: '通讯异常，5秒后尝试重连',type: 'error'});
                if (this.ws) {
                    this.ws.close();
                    this.ws = null;
                    this.panduanFlag = false
                    this.lianjieTitle = '连接'
                    clearTimeout(this.changshi)
                    this.changshi = setTimeout(() => {
                        this.connect()
                    },5000)
                }
            };
        },
        //发送信息
        sendMessage() {
                // 发送消息
                if (this.ws && this.ws.readyState === WebSocket.OPEN) {
                    // 假设我们要发送的参数是一个对象
                    const params = 'monitor';
                    // 将对象转换为JSON字符串
                    // const message = JSON.stringify(params);
                    this.ws.send(params);
                    // console.log('发送消息：', params);
                } else {
                    console.log('WebSocket连接未打开，无法发送消息');
                }
        },
        //关闭连接
        disconnect() {
                // 断开WebSocket连接
                if (this.ws) {
                    const params = 'close';
                    this.ws.send(params);
                    this.ws.close();
                    this.ws = null;
                    this.panduanFlag = false
                    this.lianjieTitle = '连接'
                }
        },
        //开始保存源码
        startSaving(type,row){
        //    console.log("类型",type);
           if(Object.keys(this.nowDeviceItem).length === 0){
             return
           }
           
          if(type == 1){
                // if (this.timerNull) return
                
                this.startTime = Date.now() - this.elapsedTime
                this.timerNull = setInterval(() => {
                    // console.log("最大值的计时");
                    this.elapsedTime = Date.now() - this.startTime
                    const totalSeconds = Math.floor(this.elapsedTime / 1000)
                    const hours = Math.floor(totalSeconds / 3600)
                    const minutes = Math.floor((totalSeconds % 3600) / 60)
                    const seconds = totalSeconds % 60
                    this.formattedTime =  `${this.padTime(hours)}:${this.padTime(minutes)}:${this.padTime(seconds)}`

                }, 1000)
                if(this.leftType == '设备'){
                  var myIndex = this.deviceDataAll.findIndex(item => item.channel_number == this.nowDeviceItem.channel_number && item.device_number == this.nowDeviceItem.device_number)
                  this.deviceDataAll[myIndex].download = true
                //   this.rowsNumber = this.deviceDataAll[myIndex].messageListAll.length
                }else {
                  var myIndex = this.channelDataAll.findIndex(item => item.channel_number == this.nowDeviceItem.channel_number)
                  this.channelDataAll[myIndex].download = true
                //   this.rowsNumber = this.channelDataAll[myIndex].messageListAll.length
                }
                this.contextMenuVisible = false;
                this.downloadFlag = true
          }else {//窗口化
            //   console.log("当前",row);
              if(row.leftType == '设备'){
                 var myindex = this.deviceDataAll.findIndex(item => item.device_number == row.device_number)
                 this.deviceDataAll[myindex].download = true
                 this.deviceDataAll[myindex].contextMenuVisible = false
                //  this.deviceDataAll[myindex].rowsNumber = this.deviceDataAll[myindex].messageListAll.length
                //  console.log("全部设备",this.deviceDataAll);
                this.jishiqi(this.deviceDataAll[myindex])
              }else if(row.leftType == '通道'){
                //  console.log("全部通道",this.channelDataAll);
                 var myindex = this.channelDataAll.findIndex(item => item.channel_number == row.channel_number)
                 this.channelDataAll[myindex].download = true
                 this.channelDataAll[myindex].contextMenuVisible = false
                 this.jishiqi(this.channelDataAll[myindex])
                //  this.channelDataAll[myindex].rowsNumber = this.channelDataAll[myindex].messageListAll.length
              }
          }
        },
        //计时器
        jishiqi(row){
            var elapsedTime  = 0
            var startTime = Date.now() - elapsedTime
            row.timerNull = setInterval(() => {
                    elapsedTime = Date.now() - startTime
                    const totalSeconds = Math.floor(elapsedTime / 1000)
                    const hours = Math.floor(totalSeconds / 3600)
                    const minutes = Math.floor((totalSeconds % 3600) / 60)
                    const seconds = totalSeconds % 60
                    row.formattedTime =  `${this.padTime(hours)}:${this.padTime(minutes)}:${this.padTime(seconds)}`

            }, 1000)
        },
        //下载阶段性报文
        downloadPhased(type,row){
            var txtListAll = []
            var txtStartTime = ""
            var nowName = ""
            var mytype = ""
            var nowRow = {}
            var rowsNum = 0
            if(type == 1){
               rowsNum = this.rowsNumber
               nowName = this.nowDeviceItem.treeName
               mytype = this.leftType
               nowRow = this.nowDeviceItem
               this.downloadFlag = false
            }else {
                // console.log("窗口化",row);
                var nowName = row.device_name
                mytype = row.leftType
                nowRow = row
                rowsNum = row.rowsNumber
            }
            
            if(mytype == '设备'){
                  var myIndex = this.deviceDataAll.findIndex(item => item.device_number == nowRow.device_number)
                  this.deviceDataAll[myIndex].download = false
                  txtListAll = this.deviceDataAll[myIndex].messageListAll 
                  this.deviceDataAll[myIndex].formattedTime = '00:00:00' 
                  if(this.deviceDataAll[myIndex].timerNull){
                      clearInterval(this.deviceDataAll[myIndex].timerNull)
                  }
            }else {
                  var myIndex = this.channelDataAll.findIndex(item => item.channel_number == nowRow.channel_number)
                  this.channelDataAll[myIndex].download = false
                  txtListAll = this.channelDataAll[myIndex].messageListAll
                  this.channelDataAll[myIndex].formattedTime = '00:00:00' 
                  if(this.channelDataAll[myIndex].timerNull){
                      clearInterval(this.channelDataAll[myIndex].timerNull)
                  }
            }
           
            this.downloadTimeTXT(nowName,txtListAll)

           setTimeout(() => {
             if(mytype == '设备'){
                  var myIndex = this.deviceDataAll.findIndex(item => item.device_number == nowRow.device_number)
                 this.deviceDataAll[myIndex].messageListAll  = []
                }else {
                    var myIndex = this.channelDataAll.findIndex(item => item.channel_number == nowRow.channel_number)
                    this.channelDataAll[myIndex].messageListAll = []
                }
           },1000)

        },
        //下载报文
        downloadTimeTXT(name,allList){
             // 提取所有 msg 内容
            const textContent = allList.map(item => item.msg).join('\n');
            // console.log("msg内容",textContent);

            // 创建一个 Blob 对象
            const blob = new Blob([textContent], { type: 'text/plain' });

            // 生成一个 URL
            const url = URL.createObjectURL(blob);

            // 创建一个隐藏的 <a> 标签
            const a = document.createElement('a');
            a.style.display = 'none';
            a.href = url;

            // 设置下载的文件名
            a.download = `${name}.txt`;

            // 将 <a> 标签添加到 DOM 中
            document.body.appendChild(a);

            // 触发点击事件
            a.click();

            // 移除 <a> 标签
            document.body.removeChild(a);

            // 释放 URL 对象
            URL.revokeObjectURL(url);

        },
        
        //转换时间戳
        timefn(value){
            if(!value) {
            return ""
            }
            let date=new Date(value);
            let Y=date.getFullYear()+'-';
            let M=(date.getMonth()+1<10? '0'+(date.getMonth()+1):date.getMonth()+1)+'-';
            let D=(date.getDate()<10? '0'+(date.getDate()):date.getDate())+' ';

            let h=(date.getHours()<10? '0'+(date.getHours()):date.getHours())+'.';
            let m=(date.getMinutes()<10? '0'+(date.getMinutes()):date.getMinutes())+'.';
            let s=(date.getSeconds()<10? '0'+(date.getSeconds()):date.getSeconds());
            let strDate=Y+M+D+h+m+s;
            return strDate
        }
  },
};
</script>
<style lang="scss" scoped>
    .messageviewing {
          width: 100%;
          height: 100%;
          .con {
              width: 100%;
              height: 100%;
              background-color: #fff;
              display: flex;
            .left-tree {
                  width: 280px;
                  height: 100%;
                  border-right: 1px solid #E6E6E6;
                  padding: 12px;
                  box-sizing: border-box;

            }
            .right-table {
                  width: calc(100% - 280px);
                  height: 100%;
                  padding: 0px 12px;
                  box-sizing: border-box;
                 
                  .topradio {
                     margin-top: 20px;
                     display: flex;
                     align-items: center;
                     justify-content: space-between;
                  }
                  .rightcon {
                     width: 100%;
                     height: calc(100% - 80px);
                     background-color: #1A1A1A;
                     border-radius: 4px;
                     margin-top: 12px;
                     padding: 20px 0px;
                     box-sizing: border-box;
                     color: #fff;
                     font-size: 14px;
                      position: relative;
                     :deep(.el-scrollbar__thumb) {
                       background-color:#52779a;
                     }
                     :deep(.el-scrollbar__view) {
                         white-space: wrap;
                     }
                    
                  }

            }
            // 右键菜单
            .context-menu {
            position: absolute;
            background-color: white;
            border: 1px solid #ccc;
            box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.2);
            z-index: 1000;
            }

            .context-menu ul {
            list-style: none;
            padding: 0;
            margin: 0;
            }

            .context-menu li {
                color: #1A1A1A;
                padding: 8px 16px;
                cursor: pointer;
            }

            .context-menu li:hover {
            background-color: #dedede;
            }
            .conitem {
                       width: 100%;
                    //    height: 30px;
                       padding:12px;
                       box-sizing: border-box;
                       border-bottom: 1px dashed #515151;
                    //    margin-bottom: 15px;
                       .texts {
                           user-select: text;

                       }
            }
          }
    }
    :deep(.chuangkou ){
         width: 100%;
         height: 100%;
         position: relative;
    }
    .dounrow {
        position: absolute;
        top: 8px;
        right: 45px;
        display: flex;
        align-items: center;
        .downtxt {
                    white-space: nowrap;
                    font-size: 14px;
                    color: #fff;
                    margin-right: 12px;
            }
            :deep(.el-input__inner) {
                 height: 27px;
                 line-height: 27px;
            }
    }
    .xiazaiyuanma {
        font-size: 14px;
        padding: 3px 10px;
        cursor: pointer;
        margin-left: 20px;
        border: 1px solid #fff;
        border-radius: 4px;
        color: #fff;
    }
    .right-btn { 
        display: flex;
        .rownum {
            display: flex;
            align-items: center;
            margin-right: 20px;
            height: 32px;
            .downtxt {
                    white-space: nowrap;
                    font-size: 14px;
                    margin-right: 12px;
            }
            :deep(.el-input__inner) {
                 height: 32px;
                 line-height: 32px;
            }
        }
        
         .btn-item {
             min-width: 72px;
             width: 72px;
             height: 28px;
             text-align: center;
             line-height: 28px;
             font-size: 12px;
             background-color: #2178F1;
             color: #FFF;
             border-radius: 4px;
             cursor: pointer;
             margin-left: 12px;
        }
        .zanting {
           background-color: #e6a23c;
        }
        .qingkong {
          background-color: #909399;
           
        }
    }
</style>